package com;

import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy;

class Caller extends Thread
{
	String name;
	
	public Caller(String name)
	{
		this.name = name;
	}
	
	public void run(){
		SemaphoreIsolatedDemo c = new SemaphoreIsolatedDemo(name);
		c.execute();
	}
}

public class SemaphoreIsolatedDemo extends HystrixCommand<String> {

	private String name;	
	public SemaphoreIsolatedDemo(String name) {
		super(Setter.withGroupKey(HystrixCommandGroupKey.Factory
				.asKey("ThreadIsolatedDemo"))  );
		this.name = name;
	}

	protected String run() throws Exception {
		System.out.println("In Run Name is：" + name);
	
		return name;
	}

	protected String getFallback() {
		System.out.println("In GetFallBack, name is:" + name);
		return name;
	}
	
	public static void main(String[] args) {
		//不开启断路器
		ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.circuitBreaker.forceOpen", "false");
		ConfigurationManager.getConfigInstance().setProperty(
				"hystrix.command.default.execution.isolation.strategy",
				ExecutionIsolationStrategy.SEMAPHORE);
		// 设置最大并发数是2
		ConfigurationManager
				.getConfigInstance()
				.setProperty(
						"hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests",
						2);

//        //不能用异步的方式调用  				
//		for(int ind = 1; ind <= 3; ind++) {
//		    SemaphoreIsolatedDemo demo = new SemaphoreIsolatedDemo(Integer.valueOf(ind).toString());
//		    demo.queue();
//		}
		
		//开启4个线程同时调用
		for (int ind = 1; ind < 5; ind++) {
			new Caller(Integer.valueOf(ind).toString()).start();			
			
		}
	}
}
